
import 'dart:async';
import 'dart:io';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_log_util.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'ab_loading.dart';


class ABStoreKit {
  // singleton
  static final ABStoreKit _singleton = ABStoreKit._internal();
  factory ABStoreKit() {
    return _singleton;
  }

  ABStoreKit._internal();

  startListen() {
    _initPurchaseSubscription();
  }

  Future<bool> isAvailable() async {
    return await InAppPurchase.instance.isAvailable();
  }

  // properties
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  _initPurchaseSubscription() {
    final Stream<List<PurchaseDetails>> purchaseUpdates = InAppPurchase.instance.purchaseStream;
    _subscription = purchaseUpdates.listen((List<PurchaseDetails> purchases) {
      _listenToPurchaseUpdated(purchases);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error here.
      dismissLoading();
    });
  }

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
    for (var purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        loading(msg: "Pending...");
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          toast("Purchase Error");
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          await _remoteValidatePurchase(purchaseDetails);
          InAppPurchase.instance.completePurchase(purchaseDetails);
        } else if (purchaseDetails.status == PurchaseStatus.canceled) {
          toast("Purchase Canceled");
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await InAppPurchase.instance
              .completePurchase(purchaseDetails);
        }
      }
    }
  }

  purchaseProduct(String productId) async {
    var order = await api.createGoodsOrder(productId);
    LogPvManger.stat(page: 'createorder');
    var sp = await SharedPreferences.getInstance();
    sp.setString("orderNo", order.orderNo ?? '');
    loading(msg: "Purchasing...");
    try {
      var products = await InAppPurchase.instance.queryProductDetails({productId});
      if (products.productDetails.isEmpty) {
        toast("Product Not Found");
        return;
      }
      InAppPurchase.instance.buyConsumable(purchaseParam: PurchaseParam(productDetails: products.productDetails.first));
    } catch (e) {
      toast("Purchase Error");
    }
  }

  Future<bool> _remoteValidatePurchase(PurchaseDetails details) async {
    await api.verifyPurchase(details.verificationData.serverVerificationData,details.purchaseID);
    await api.fetchCoin();
    return true;
  }
}

class StoreKitEvent {
}